#!/usr/bin/env python
# -*- coding:utf-8 -*-

#./autobuild.py -p youproject.xcodeproj
#./autobuild.py -w youproject.xcworkspace

import argparse
import subprocess
import requests
import os
import datetime


import sys
import smtplib
from email.mime.text import MIMEText
from email.header import Header



# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~打包上传配置~~~~~~~~~~~~~~~~~~~~~~~

# configuration for iOS build setting
# 配置Debug 或者release
CONFIGURATION = "Release"
EXPORT_OPTIONS_PLIST = "exportOptions.plist"

# 发布版本号
VERSION = '1.0.0'
BUILDID = 'com.antubang.ATBSecurityNew'

# 要打包的TARGET名字
TARGET = 'ATBSecurity'

# Info.plist路径
PLIST_PATH = "~/Desktop/替比网络/code/ATBNoStaticLib/ATBSecurity/ATBSecurity/ATBSecurity/Info.plist"

# 存放路径以时间命令
DATE = datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')

# 会在桌面创建输出ipa文件的目录
EXPORT_MAIN_DIRECTORY = "~/Desktop/" + TARGET + DATE

# xcarchive文件路径（含有dsym），后续查找BUG用途
ARCHIVEPATH = EXPORT_MAIN_DIRECTORY + "/%s%s.xcarchive" %(TARGET,VERSION)

# ipa路径
IPAPATH = EXPORT_MAIN_DIRECTORY + "/%s.ipa" %(TARGET)

# configuration for pgyer
PGYER_UPLOAD_URL = "https://www.pgyer.com/apiv1/app/upload"
DOWNLOAD_BASE_URL = "https://www.pgyer.com"
USER_KEY = "7b3bde219da099a6a3575befe4f2b409"
API_KEY = "ab21b23a89714253e8e3a42cf8fc5fff"
# 设置从蒲公英下载应用时的密码
PYGER_PASSWORD = ""


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~发送邮件配置~~~~~~~~~~~~~~~~~~~~~~~

# 发件人的的账号 - 可以改动
sender = '895111863@qq.com'

# 接收邮件，可设置为你的QQ邮箱或者其他邮箱 - 可以改动
#川姐   1007949887@qq.com   马欢 172507392@qq.com
receivers = ['1835064412@qq.com' , '3208628698@qq.com', '1061070468@qq.com' , '1007949887@qq.com' , '172507392@qq.com']


# 配置发送人的邮箱数据 - 不要改动
username = '895111863@qq.com'
password = 'papdmswgcxmlbfbd'

# SMTP邮箱服务器 - 不要改动
mail_host = 'smtp.qq.com'

def send_mail(title, content):
    try:
        msg = MIMEText(content,'plain','utf-8')
        if not isinstance(title,unicode):
            title = unicode(title, 'utf-8')
        msg['Subject'] = title
        msg['From'] = sender
        msg['To'] = Header(''.join(receivers), 'utf-8')
        msg["Accept-Language"]="zh-CN"
        msg["Accept-Charset"]="ISO-8859-1,utf-8"
        
        smtp = smtplib.SMTP_SSL()
        smtp.connect(mail_host, 465)  # 465 为 SMTP 端口号
        smtp.login(username, password)
        smtp.sendmail(sender, receivers, msg.as_string())
        smtp.quit()
        print "邮件发送成功!"

    except Exception, e:
        print str(e)
        print "邮件发送失败!"



def cleanArchiveFile():
    cleanCmd = "rm -r %s" %(ARCHIVEPATH)
    process = subprocess.Popen(cleanCmd, shell = True)
    process.wait()
    print "cleaned archiveFile: %s" %(ARCHIVEPATH)

def parserUploadResult(jsonResult):
    resultCode = jsonResult['code']
    if resultCode == 0:
        downUrl = DOWNLOAD_BASE_URL +"/"+jsonResult['data']['appShortcutUrl']
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        print "😁😁😁😁恭喜您上传成功Upload Success"
        print "DownUrl is:" + downUrl
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"


        print "开始测试分发给XC人员"
        emailTitle  = "安途帮的新版本已经更新啦，你可以下载来看啦"
        emailContent  = downUrl

        send_mail(emailTitle,emailContent)
    
    else:
        print "😭😭😭😭上传失败Upload Fail!"
        print "Reason:"+jsonResult['message']

def uploadIpaToPgyer(ipaPath):
    print "ipaPath:"+ipaPath
    ipaPath = os.path.expanduser(ipaPath)
    ipaPath = unicode(ipaPath, "utf-8")
    files = {'file': open(ipaPath, 'rb')}
    headers = {'enctype':'multipart/form-data'}
    payload = {'uKey':USER_KEY,'_api_key':API_KEY, 'password':PYGER_PASSWORD}
    print "正在努力上传中，请稍后uploading...."
    r = requests.post(PGYER_UPLOAD_URL, data = payload ,files=files,headers=headers)
    if r.status_code == requests.codes.ok:
        result = r.json()
        parserUploadResult(result)
    else:
        print 'HTTPError,Code:'+r.status_code

def exportArchive():
    exportCmd = "xcodebuild -exportArchive -archivePath %s -exportPath %s -exportOptionsPlist %s" %(ARCHIVEPATH, EXPORT_MAIN_DIRECTORY, EXPORT_OPTIONS_PLIST)
    process = subprocess.Popen(exportCmd, shell=True)
    (stdoutdata, stderrdata) = process.communicate()
    
    signReturnCode = process.returncode
    if signReturnCode != 0:
        print "export %s failed" %(TARGET)
        return ""
    else:
        return EXPORT_MAIN_DIRECTORY

def buildProject(project):
    archiveCmd = 'xcodebuild -project %s -scheme %s -configuration %s archive -archivePath %s -destination generic/platform=iOS' %(project, TARGET, CONFIGURATION, ARCHIVEPATH)
    process = subprocess.Popen(archiveCmd, shell=True)
    process.wait()
    
    archiveReturnCode = process.returncode
    if archiveReturnCode != 0:
        print "archive project %s failed" %(project)
        cleanArchiveFile()

def buildWorkspace(workspace):
    archiveCmd = 'xcodebuild -workspace %s -scheme %s -configuration %s archive -archivePath %s -destination generic/platform=iOS' %(workspace, TARGET, CONFIGURATION, ARCHIVEPATH)
    process = subprocess.Popen(archiveCmd, shell=True)
    process.wait()
    
    archiveReturnCode = process.returncode
    if archiveReturnCode != 0:
        print "archive workspace %s failed" %(workspace)
        cleanArchiveFile()

def xcbuild(options):
    project = options.project
    workspace = options.workspace
    
    if project is None and workspace is None:
        pass
    elif project is not None:
        buildProject(project)
    elif workspace is not None:
        buildWorkspace(workspace)
    
    #导出ipa文件
    exportarchive = exportArchive()
    if exportarchive != "":
        print "开始上传蒲公英......"
        uploadIpaToPgyer(IPAPATH)
        cleanArchiveFile()
    else:
         print "导出ipa文件失败"




def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--workspace", help="Build the workspace name.xcworkspace.", metavar="name.xcworkspace")
    parser.add_argument("-p", "--project", help="Build the project name.xcodeproj.", metavar="name.xcodeproj")
    
    options = parser.parse_args()
    
    print "options: %s" % (options)
    
    os.system('/usr/libexec/PlistBuddy -c "Set:CFBundleShortVersionString %s" %s' % (VERSION,PLIST_PATH))
    os.system('/usr/libexec/PlistBuddy -c "Set:CFBundleVersion %s" %s' % (BUILDID, PLIST_PATH))
    
    xcbuild(options)

if __name__ == '__main__':
    main()
